﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using com.fukefu.sql;

namespace com.fukefu.tools
{
    public class ArticleTag
    {
        Random random = new Random();
        Hashtable ht = new Hashtable();
        //初始化
        public ArticleTag()
        {
            SqlServerOperate sql = new SqlServerOperate();
            SqlDataReader re = sql.Query("select 全局设置.dbo.[_mb_标签分类].word as type,_mb_标签.cont from _mb_标签 left join 全局设置.dbo.[_mb_标签分类] on _mb_标签.pid=全局设置.dbo.[_mb_标签分类].pid");
            List<string> list = null;
            while (re.Read())
            {
                if (ht.Contains(re["type"]))
                {
                    list = ht[re["type"]] as List<string>;
                }
                else
                {
                    list = new List<string>();
                    ht.Add(re["type"], list);
                }
                list.Add(re["cont"].ToString());
            }
            re.Close();
            sql.Close();
        }
        //获取标签
        public string Get(string tag)
        {
            tag = tag.Replace("{tag:", "");
            tag = tag.Replace("}", "");
            List<string> list = ht[tag] as List<string>;
            if (list != null && list.Count > 0)
            {
                return list[random.Next(list.Count)];
            }
            return "";
        }
        //替换所有标签
        public string ReplaceAllTag(string content)
        {
            MatchCollection mc = Regex.Matches(content, "{tag:[^}]+}");
            foreach (Match m in mc)
            {
                GroupCollection gc = m.Groups;
                content = new Regex(gc[0].Value).Replace(content, Get(gc[0].Value), 1);
            }
            return content;
        }
    }
}
